<template>
  <v-col style="flex: 1 1 auto;" class="d-flex flex-column fill-height">
    <v-toolbar flat color="surface" class="px-4">
      <v-toolbar-title>{{ title }}</v-toolbar-title>
    </v-toolbar>

    <v-divider />

    <!-- 聊天消息区域 -->
    <div class="chat-message-container px-6 py-4" style="flex: 1 1 auto; overflow-y: auto;">
      <template v-if="messages.length">
        <MessageBubble v-for="(msg, index) in messages" :key="msg.id" :msg="msg" :currentUserId="currentUserId"
          :show-name="false" :top_round="!isSameSender(messages[index - 1], msg)"
          :bottom_round="!isSameSender(messages[index + 1], msg)" />
      </template>
      <template v-else>
        <div class="text-center text-medium-emphasis text-subtitle-1 mt-10">
          {{ loading ? '加载中...' : '暂无消息' }}
        </div>
      </template>
    </div>


    <v-divider />

    <!-- 底部输入框：固定不伸缩，始终在底部 -->
    <div class="pa-4" style="flex-shrink: 0;">
      <v-text-field v-if="props.id" v-model="message" placeholder="输入消息..." hide-details clearable rounded
        variant="outlined" color="primary" append-inner-icon="mdi-send" @click:append-inner="sendMessage" />
    </div>
  </v-col>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { getMessagesByChat } from '@/utils/indexedDb'
import MessageBubble from './MessageBubble.vue'
import { useMessageStore } from '@/stores/app'
import axios from 'axios'
import type { ChatMessage } from '@/stores/app'


watch(() => useMessageStore().messages, (val) => {
  console.log("✅ messages 更新了：", val)
}, { deep: true })

const props = defineProps<{
  name: string
  type: 'friends' | 'group'
  id: number
}>()

const emit = defineEmits<{
  (e: 'send', content: string): void
}>()

const message = ref('')
const loading = ref(false)

const messageStore = useMessageStore()
const currentUserId = Number(localStorage.getItem('user_id'))

const title = computed(() =>
  props.type === 'friends' ? `${props.name} #${props.id}` : `${props.name} #${props.id}`
)

const messages = computed<(ChatMessage & { self: boolean })[]>(() => messageStore.messages)

watchEffect(() => {
  console.log('now message', messages.value)
})

function isSameSender(a?: ChatMessage, b?: ChatMessage): boolean {
  return !!a && !!b && a.senderId === b.senderId
}


watch(
  () => [props.type, props.id],
  async ([type, id]) => {
    if (!id) return
    loading.value = true

    const realType = type === 'friends' ? 'PRIVATE' : 'GROUP'
    messageStore.setCurrentChat(id, realType)

    try {
      // console.log('indexed db find params',realType, id);
      const list = await getMessagesByChat(realType, id)
      console.log('messages from indexedDB', list)
      messageStore.setMessages(list)
    } catch (e) {
      console.error('❌ 加载消息失败:', e)
      messageStore.setMessages([])
    } finally {
      loading.value = false
    }
  },
  { immediate: true }
)

async function sendMessage() {
  const content = message.value.trim()
  if (!content) return

  const senderId = Number(localStorage.getItem('user_id'))
  if (!senderId || !props.id) {
    console.warn('❌ 缺少 senderId 或目标 ID')
    return
  }

  try {
    if (props.type === 'group') {
      await axios.post(
        'http://localhost:8080/api/group/room/send',
        null,
        {
          params: {
            senderId,
            roomId: props.id,
            content,
          },
          auth: {
            username: 'admin',
            password: '123456',
          },
        }
      )
    } else {
      await axios.post(
        'http://localhost:8080/api/messages/send',
        { content },
        {
          params: {
            senderId,
            receiverId: props.id,
          },
          headers: {
            'Content-Type': 'application/json',
          },
          auth: {
            username: 'admin',
            password: '123456',
          },
        }
      )
    }

    const currentUserId = Number(localStorage.getItem('user_id') ?? -1)
    console.log('message type', props.type)
    if (props.type === 'friends' && senderId === currentUserId) {
      useMessageStore().saveMessage({

        senderId: senderId,
        senderName: '我',
        receiverId: props.id, // 对方id或群组id
        type: props.type === 'friends' ? "PRIVATE" : "GROUP",
        content: content,
        timestamp: new Date().toISOString(),
      })
    }

    console.log('✅ 消息发送成功')
  } catch (error) {
    console.error('❌ 消息发送失败', error)
  }

  emit('send', content)
  message.value = ''
}
</script>

<style scoped>
.chat-message-container {
  flex: 1 1 auto;
  overflow-y: auto;
  max-height: calc(100vh - 180px);
}
</style>